﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using EqRepair.Code.Data;
using EqRepair.Code.Enums;

namespace EqRepair.Code.Classes
{
    public static class AccessData
    {
        public static int GetSystemID()
        {
            return 33;
        }
        public static void AddUser(string Login, string Passw)
        {
            using (var db = new DataClasses2DataContext())
            {
                var d = new Employee
                            {
                                Login = Login,
                                PasswordSHA1 = Helper.GetHash(Passw),
                                ChiefId = 0,
                                FullName = Login,
                                Role = 1
                            };
                db.Employees.InsertOnSubmit(d);
                db.SubmitChanges();
            }
        }
        public static void AddUser(string Login, string Passw, int Chief, int Role, string FullName)
        {
            using (var db = new DataClasses2DataContext())
            {
                var d = new Employee
                                {
                                    Login = Login,
                                    PasswordSHA1 = Helper.GetHash(Passw),
                                    ChiefId = Chief,
                                    FullName = FullName,
                                    Role = Role
                                };
                db.Employees.InsertOnSubmit(d);
                db.SubmitChanges();
            }
        }
        public static void MoveSubAgregatToOrgEq(EquipmentInOrganization EquipOId)
        {
            MoveSubToOrgEq(EquipOId);
        }
        public static void MoveSubToOrgEq(EquipmentInOrganization EquipOId)
        {
            using (var db = new DataClasses2DataContext())
            {

                int eqId = EquipOId.EquipmentId;
                foreach (var sub in db.EquipmentHierarchies.Where(x => x.ParentEquipmentId == eqId))// EquipOId.Equipment.EquipmentHierarchies)
                {
                    for (int i = 0; i < sub.Count; ++i)
                    {
                        EquipmentInOrganization eq = new EquipmentInOrganization();
                        eq.Description = EquipOId.Description;
                        eq.EquipmentId = sub.ChildEquipmentId;
                        eq.InstallDate = EquipOId.InstallDate;
                        eq.OrganizationId = EquipOId.OrganizationId;
                        eq.ParentID = EquipOId.Id;
                        db.EquipmentInOrganizations.InsertOnSubmit(eq);
                        db.SubmitChanges();
                        MoveSubToOrgEq(eq);
                    }
                }
            }

        }

        public static int? GetChiefCurUser(int idi)
        {
            using (var db = new DataClasses2DataContext())
            {

                return db.Employees.First(x => x.Id == idi).ChiefId;
            }
        }

        public static TreeNode GetTreeAgregInOrg(int idi)
        {
            TreeNode NewN;
            using (var db = new DataClasses2DataContext())
            {
                var FirstAg = db.EquipmentInOrganizations.FirstOrDefault(x => x.Id == idi);
                NewN = new TreeNode(FirstAg.Equipment.Name, FirstAg.Id.ToString());
                foreach (var Uz in db.EquipmentInOrganizations.Where(x => x.ParentID == idi))
                {
                    NewN.ChildNodes.Add(GetTreeAgregInOrg(Uz.Id)); //new TreeNode(Uz.Id.ToString(),Uz.Equipment.Name));

                }
            }
            return NewN;
        }

        public static int DiferInDay(DateTime dt1, DateTime dt2)
        {
            return (dt1.Year * 365 + dt1.DayOfYear) - (dt2.Year * 365 + dt2.DayOfYear);
        }

        public static void CreateAutoReq()
        {
            //расчет всех след дат ремонта
            using (var db = new DataClasses2DataContext())
            {
                foreach (var Uz in db.EquipmentInOrganizations)
                {
                    if (Uz.NextRepairDate == null || Uz.NextRepairDate == new DateTime(1, 1, 1, 0, 0, 0))
                    {
                        //ставим след дату
                        if (Uz.LastRepairDate == null || Uz.LastRepairDate == new DateTime(1, 1, 1, 0, 0, 0))
                        {
                            Uz.NextRepairDate = Uz.InstallDate.AddDays((int)Uz.Equipment.LifeTime);
                        }
                        else
                        {
                            Uz.NextRepairDate = ((DateTime)Uz.LastRepairDate).AddDays((int)Uz.Equipment.LifeTime);
                        }
                    }
                }
                db.SubmitChanges();


                //Получим все железо с след датой рема = тек дате (15 дней)
                foreach (var Uz in db.EquipmentInOrganizations)
                {
                    if (DiferInDay((DateTime)Uz.NextRepairDate, DateTime.Now) < 15)
                    {
                        //проверим- нет ли незакр заявок
                        EquipmentInOrganization uz = Uz;
                        if (db.RequestForRepairs.Where(x => x.EquipmentInOrganization.Id == uz.Id && (x.Status == 1 || x.Status == 2)).Count() == 0)
                        {
                            //добавим
                            var rr = new RequestForRepair
                            {
                                CreatedById = GetSystemID(),
                                Status = ((short)StatusRequest.New),
                                CreatedDateTime = DateTime.Now,
                                OrganizationEquipmentId = Uz.Id,
								Descr = "Плановое обслуживание"
                            };
                            db.RequestForRepairs.InsertOnSubmit(rr);
                            db.SubmitChanges();
                        }
                    }
                }
            }
        }

        public static void DelSubAgr(EquipmentInOrganization eq)
        {
            using (var db = new DataClasses2DataContext())
            {

                int eqId = eq.Id;
                foreach (var sub in db.EquipmentInOrganizations.Where(x => x.ParentID == eqId))// EquipOId.Equipment.EquipmentHierarchies)
                {
                    DelSubAgr(sub);
                    db.EquipmentInOrganizations.DeleteOnSubmit(sub);
                    db.SubmitChanges();

                }

            }
        }

        public static string GetIDFullParent(EquipmentInOrganization eq)
        {
            int curA;
            curA = eq.Id;
            string ret;
            using (var db = new DataClasses2DataContext())
            {
                //int curA = ;
                int curPar = db.EquipmentInOrganizations.Where(x => x.Id == curA).First().ParentID.Value;
                while (curPar != 0)
                {
                    int curPar1 = curPar;
                    curA = db.EquipmentInOrganizations.Where(x => x.Id == curPar1).First().Id;
                    curPar = db.EquipmentInOrganizations.Where(x => x.Id == curA).First().ParentID.Value;
                }

                ret = db.EquipmentInOrganizations.Where(x => x.Id == curA).FirstOrDefault().Equipment.Name;
            }
            return ret;
        }
        /// <summary>
        /// ПОлучить абстрактную иерархию на основе справочника деталей
        /// </summary>
        /// <param name="idi">код Агрегата</param>
        /// <returns>Иерархия TreeNode</returns>
        public static TreeNode GetTreeAgregInEq(int idi)
        {
            TreeNode NewN;
            using (var db = new DataClasses2DataContext())
            {
                var CurrentN = db.Equipments.FirstOrDefault(x => x.Id == idi);
                NewN = new TreeNode(CurrentN.Name, CurrentN.Id.ToString());
                foreach (var sub in db.EquipmentHierarchies.Where(x => x.ParentEquipmentId == idi))
                {
                    for (int i = 0; i < sub.Count; ++i)
                    {
                        NewN.ChildNodes.Add(GetTreeAgregInEq(sub.ChildEquipmentId));
                    }
                }
                return NewN;
            }
        }
    }
}
